package ltd.followkba.task;

import com.kcbsdk.MyWorks.APhotoInfo;
import com.kcbsdk.MyManage.AUserFileType;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import ltd.advskin.MRAM;
import ltd.advskin.task.TaskApp21;
import ltd.advskin.utils.SubUtils;
import ltd.advskin.utils.SysUtils;
import ltd.followkba.MAPP;
import ltd.followkba.comment.MUTIL;
import ltd.followkba.comment.ResultNet;

import ltd.followkba.comment.utils.CodeBase64;
import main.MAPI;

import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static ltd.followkba.comment.MKCC.*;


public class App33 {
    public static byte AppType;
    public static String gsUserID;
    public static String gsToken;
    public static String LoginFlag;
    public static String gsLongitude;
    public static String gsLatitude;
    public static String gsMac;
    public static String gsUserAgent;
    public static String gs_cli_model;
    public static String gs_cli_uniqid;
    public static String gsDevice;
    public static String gsVersion;
    public static String gsImei;
    public static String gsLast;
    public static String gsAuthSsid;
    public static String gsAuthFile;

    public static String gsApiError;

    public static void MLOG(String text) {
        MSTRING("App33 " + text);
    }

    public static synchronized void setUser(BDbsAccount bDbsAccount){
        String loginFlag = (bDbsAccount != null) ? bDbsAccount.LoginFlag : MAPP.getLoginFlag(33);
        if (loginFlag != null) {
            String[] params = loginFlag.split(":");
            if (params.length > 1) {
                setUser(params[0], "T" + params[1]);
            }
        }
    }
    public static synchronized void setUser(String userID, String token){
        if ((userID != null) && (token != null) && (!userID.equals(gsUserID)) && (!token.equals(gsToken))){
            gsUserID = userID;
            gsToken = token;
            gsAuthFile = MRAM.gsCachePath + "AuthCode.png";
            SysUtils sysUtils = new SysUtils();
            String gsLocal_1 = gsUserID != null ? gsUserID : "";
            gsLocal_1 = sysUtils.getStringMd5(gsLocal_1);
            gsLocal_1 = gsLocal_1.toUpperCase();
            long checksum1 = MAPI.GET_SPEC_DWORD_CHECKSUM(gsLocal_1.getBytes().length, 0, gsLocal_1.getBytes());
            gsDevice = String.format("%s-%04d", MUTIL.GET_MOBIL_BRAND((int) (checksum1 & 0x0fffffff)).substring(0, 2).toUpperCase(), remainder(checksum1, 10000));
            gsVersion = String.format("&version=10.%s.%s", remainder(checksum1 >> 6, 10), remainder(checksum1 >> 2, 10));
            StringBuffer stringBuffer = new StringBuffer(gsLocal_1);
            int g4Local_1 = 2;
            do {
                stringBuffer.insert(g4Local_1, "%3A");
                g4Local_1 += 3 + 2;
            } while (g4Local_1 < 27);
            gsMac = stringBuffer.toString().substring(0, 27);
            gsMac = gsMac.toUpperCase();
            long checksum2 = MAPI.GET_SPEC_DWORD_CHECKSUM(gsMac.getBytes().length, 0, gsMac.getBytes());

            gsImei = String.format("%s", (checksum1 << 32) | checksum2);
            if (gsImei.length() > 16) {
                gsImei = gsImei.substring(0, 15);
            }
            String smdeviceid = String.format("2021%02d%02d%02d%02d%02d", 1 + remainder(checksum1, 11), 1 + remainder(checksum1, 27), remainder(checksum1, 24), remainder(checksum1, 60), remainder(checksum2, 60));
            smdeviceid = String.format("%s%s%s", smdeviceid, sysUtils.getStringMd5(MRAM.gsCachePath), sysUtils.getStringMd5(gsMac));
            if (smdeviceid.length() > 62) {
                smdeviceid = smdeviceid.substring(0, 62);
            }
            gsLast = "&org_install_channel=market_%E5%B0%8F%E7%B1%B3&ismember=0&channelsrc=market_%E5%B0%8F%E7%B1%B3&smdeviceid=" + smdeviceid + "&deviceid=" + gsMac + "&bless=1&oaid=";
            gsUserAgent = String.format("Dalvik/1.6.%s (Linux; Android 8.%s; %s Build/JSS%02dJ)", remainder(checksum2 >> 4, 10), remainder(checksum2, 10), gsDevice, remainder(checksum2, 100));
        MLOG(String.format("gsUserID:%s(%s) gsUserAgent:%s gsVersion:%s ", gsUserID, checksum2, gsUserAgent, gsVersion));
        MLOG(String.format("LoginFlagA :%s %s", gsUserID, gsToken));
        }
    }
    //    public App33(String loginFlag, int userID, int worksType) {
//        startRun(loginFlag, userID, worksType);
//    }
    public static synchronized String getApiError(){
        return gsApiError;
    }
    private static synchronized int remainder(long value, int mode){
        int temp = (int)(value % mode);
        if (temp < 0){
            return 0 - temp;
        }
        return temp;
    }

    public static synchronized String checkLogin(){
        String destUrl = getLast(String.format("ktvbox.php?ac=getwochangbastatus&specialurl=uni"));
        String result = writeApi(destUrl);
        if (result != null) {                                                           // 联通沃
            return "ok";
        }
        return gsApiError;
    }
    public static synchronized String loginSvr(String account, String password, String authCode, BDbsAccount bDbsAccount){
        String gsLocal_1 = MUTIL.GET_MD5_STRING(gsAuthSsid + "ba!se");
        String gsLocal_2 = gsLocal_1.substring(0, 10);
        gsLocal_1 = MUTIL.GET_MD5_STRING(password);
        String gsLocal_3;
        if (authCode.startsWith("c2")){
            gsLocal_3 = "";
        }
        else {
            gsLocal_3 = URLEncoder.encode(authCode);
        }
//        https://secure.changba.com/
        String destUrl = "ktvboxs.php?ac=llogin&md5pwd=" + gsLocal_1 + "&email="+account+"&ssid="+gsLocal_2+"&captcha=" + gsLocal_3;
        destUrl += "&channelsrc=changba&deviceid="+ gsMac +"&bless=1&macaddress="+ gsMac +gsVersion;

        TaskApp21 taskApp21 = new TaskApp21();
        String userinfo = taskApp21.getSeret(gsUserID, gsToken, "https://secure.changba.com/"+destUrl);
//        MLOG("resultA1 "+destUrl);        MLOG("resultA2 "+userinfo);
//        String url = taskApp21.makeV2(1, destUrl+userinfo);     // V1 = "http://api.changba.com/"+destUrl+userinfo;
        String url = "https://secure.changba.com/" + destUrl+userinfo;
//        MLOG("resultA3 "+url);
        SysUtils sysUtils = new SysUtils();
        gsLocal_1 = sysUtils.getHttpsString(url);
//        MLOG("resultA5 "+gsLocal_1);
        String errorcode = sysUtils.getJsonString(gsLocal_1, "errorcode");
        String result = sysUtils.getJsonString(gsLocal_1, "result");
        if ("ok".equals(errorcode)) {
            gsUserID = MUTIL.GET_JSON_STRING(result, "userid");
            gsToken = MUTIL.GET_JSON_STRING(result, "token");
            if (!"".equals(gsUserID) && !"".equals(gsToken)) {
                LoginFlag = gsUserID + ":" + gsToken.substring(1, gsToken.length());
                MLOG(String.format("resultA6 %s %s", LoginFlag, gsToken));
                bDbsAccount.Status = "ok";
                bDbsAccount.UserIdS = gsUserID;
                bDbsAccount.UserID = MAPI.STRING_DEC32(gsUserID);
                bDbsAccount.LoginFlag = LoginFlag;
                return "ok";
            }
        }
        return errorcode;
    }
    public static synchronized BAppUser getUserInfo(String userIdS){
        SysUtils sysUtils = new SysUtils();
        BAppUser bAppUser;
        String destUrl = getLast(String.format("ktvbox.php?ac=getuserinfo&userid=%s", userIdS));
        String result = writeApi(destUrl);
        if (result != null) {
            bAppUser = new BAppUser();
            bAppUser.WorksType = 33;
            bAppUser.UserIdS = userIdS;
            bAppUser.UserName = sysUtils.getJsonString(result, "nickname");
            bAppUser.ChangBaID = sysUtils.getJsonString(result, "accountid");
            bAppUser.Gender = sysUtils.getJsonInt(result, "gender");
            bAppUser.Intro = sysUtils.getJsonString(result, "title");
            if ("".equals(bAppUser.Intro)) {
                bAppUser.Intro = sysUtils.getJsonString(result, "signature");
            }
            bAppUser.HeadUrl = sysUtils.getJsonString(result, "headphoto");
            bAppUser.Birthday = sysUtils.getJsonString(result, "birthday");
            String location = sysUtils.getJsonString(result, "location");
            if (!"".equals(location)) {
                location = location.replace("+", " ");
                String[] split = location.split(" ");
                if (split.length > 0) {
                    bAppUser.Province = split[0];
                    if (split.length > 1) {
                        bAppUser.City = split[1];
                    }
                } else {
//                    MLOGE(String.format("App33 location:%s", location));
                }
            } else {
                bAppUser.Province = sysUtils.getJsonString(result, "province");
                bAppUser.City = sysUtils.getJsonString(result, "city");

            }
            bAppUser.longitude = sysUtils.getJsonString(result, "longitude");
            bAppUser.latitude = sysUtils.getJsonString(result, "latitude");

            destUrl = getLast(String.format("ktvbox.php?ac=getuserrelationnum&userid=%s", userIdS));
            result = writeApi(destUrl);
            if (result != null) {
                bAppUser.FansQty = sysUtils.getJsonInt(result, "fansnum");
                bAppUser.CareQty = sysUtils.getJsonInt(result, "friendsnum");
            }
            destUrl = getLast(String.format("ktvbox.php?ac=getuserstatistics&userid=%s", userIdS));
            result = writeApi(destUrl);
            if (result != null) {
                bAppUser.WorksQty = sysUtils.getJsonInt(result, "worknum");
                bAppUser.ListenQty = sysUtils.getJsonInt(result, "listennum");
            }
            return bAppUser;
        }
        return null;
    }
    public static synchronized String[] getWorksList(String userIdS, boolean getAll){
        SysUtils sysUtils = new SysUtils();
        List<String> lists = new ArrayList<>();
        int qty = getAll ? 10000 : 1;
        for (int index = 0; index < qty; index+=20) {
            String destUrl = getLast(String.format("ktvbox.php?ac=getmixeduserworklist&userid=%s&num=20&start=%s", userIdS, index));
            String result = writeApi(destUrl);
//            MLOG(String.format("getWorksListA A %s(%s)%s", index, lists.size(), result));
            if (!"[]".equals(result) && result != null) {
                try {
                    JSONArray jsonArray = new JSONArray(result);
                    int length = jsonArray.length();
//                    MLOG(String.format("getWorksListA B %s %s %s", index, length, result));
                    for (int counter = 0; counter < length; counter++) {
                        JSONObject jsonobject = jsonArray.getJSONObject(counter);
                        try {
                            String work = jsonobject.getString("work");
                            String text = sysUtils.getJsonString(work, "workid");
                            if (!MAPI.isEmpty(text)) {
                                lists.add(text);
                            }
                        } catch (JSONException e) {
//                            MLOGE(String.format("getWorksListA E %s %s %s", counter, index, e.toString()));
                            e.printStackTrace();
                        }
                    }
//                    MLOG(String.format("getWorksListA C %s %s", index, length));
                } catch (JSONException e) {
                    MLOGE(String.format("getWorksListA Err %s", e.toString()));
                    e.printStackTrace();
                }
            }else {
                break;
            }
        }
        if (lists.size() > 0){
//            MLOG(String.format("getWorksListA F %s", lists.size()));
            return lists.toArray(new String[lists.size()]);
        }
        return null;
    }

    public static synchronized BAppWorks getWorksInfo(String userIdS, String worksIdS){
        if (!MAPI.isEmpty(worksIdS)) {
//            ResultNet resultNet = new ResultNet();
            String destUrl = getLast(String.format("ktvbox.php?ac=getuserwork&workid=%s", worksIdS));
            String result = writeApi(destUrl);
            if (result != null) {
                SysUtils sysUtils = new SysUtils();
                BAppWorks bAppWorks = new BAppWorks();
//MLOG(String.format("makeWorksListC B %s", resultNet.nextJason));
                bAppWorks.WorksType = 33;
                bAppWorks.UserIdS = userIdS;
                bAppWorks.WorksIdS = MUTIL.GET_JSON_STRING(result, "workid");
                bAppWorks.Intro = MUTIL.GET_JSON_STRING(result, "title");
                bAppWorks.AudioUrl = MUTIL.GET_JSON_STRING(result, "workpath");
                bAppWorks.CommentQty = sysUtils.getJsonInt(result, "comment_num");// MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(result, "comment_num"));
                bAppWorks.ListenQty = sysUtils.getJsonInt(result, "listen_num");// MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(result, "listen_num"));
                bAppWorks.GiftQty = sysUtils.getJsonInt(result, "flower_num");// MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(result, "flower_num"));
                bAppWorks.ShareQty = sysUtils.getJsonInt(result, "forward_num");// MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(result, "forward_num"));
                bAppWorks.MoneyQty = sysUtils.getJsonInt(result, "money_num");
                bAppWorks.FreeQty = sysUtils.getJsonInt(result, "free_num");
                bAppWorks.LikeQty = sysUtils.getJsonInt(result, "like_num");
                bAppWorks.CreateTime = MUTIL.GET_JSON_STRING(result, "addtime");
                bAppWorks.CreateTime = MUTIL.CHANG_DATE_FORMAT(bAppWorks.CreateTime);

                String text = MUTIL.GET_JSON_STRING(result, "song");
                bAppWorks.MusicIdS = MUTIL.GET_JSON_STRING(text, "songid");
                bAppWorks.WorksName = MUTIL.GET_JSON_STRING(text, "name");
                bAppWorks.SrcTag = MUTIL.GET_JSON_STRING(text, "tag");
                bAppWorks.ArtistName = MUTIL.GET_JSON_STRING(text, "artist");
                bAppWorks.ArtistIcon = MUTIL.GET_JSON_STRING(text, "icon");
                bAppWorks.OriginalUrl = MUTIL.GET_JSON_STRING(text, "original_mp3");
                bAppWorks.MusicUrl = MUTIL.GET_JSON_STRING(text, "music");
                bAppWorks.MusicHqUrl = MUTIL.GET_JSON_STRING(text, "hq_music");
                bAppWorks.LyricUrl = MUTIL.GET_JSON_STRING(text, "zrc");

//MLOG(aSongInfo.MusicIdS + " ddd " +aSongInfo.WorksName);
                text = MUTIL.GET_JSON_STRING(result, "video");
                bAppWorks.IsVideo = false;
//MLOG(gsLocal_3);
                if (!"".equals(text)) {
                    bAppWorks.VideoUrl = MUTIL.GET_JSON_STRING(text, "videourl");
                    if ("".equals(bAppWorks.VideoUrl)) {
                        try {
                            String altlist = MUTIL.GET_JSON_STRING(text, "videourl_altlist");
                            JSONArray videoAlt = null;
                            videoAlt = new JSONArray(altlist);
                            if (videoAlt.length() > 0){
                                bAppWorks.VideoUrl = videoAlt.getString(0);
                                if ("".equals(bAppWorks.VideoUrl) && videoAlt.length() > 1){
                                    bAppWorks.VideoUrl = videoAlt.getString(1);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (!MAPI.isEmpty(bAppWorks.VideoUrl)) {
                    bAppWorks.IsVideo = true;
                }
                text = MUTIL.GET_JSON_STRING(result, "cover");
//                    MLOG(String.format("makeWorksListD %s %s ",aux1, gsLocal_3));
                bAppWorks.CoverUrl = sysUtils.getJsonString(text, "path");
                bAppWorks.CoverFile = String.format("%sC21_%s.jpg", MRAM.gsCachePath, bAppWorks.WorksIdS);
                return bAppWorks;
            }
        }
        return null;
    }



    public static synchronized BFileBase[] getRankList(String city){
        String gsLocal_1 = "";
        if (!"全国".equals(city)){
            gsLocal_1 += URLEncoder.encode(city);
        }
        String destUrl = getLast(String.format("ktvbox_apiproxy.php?ac=gethottestwork&start=0&num=96&area=%s", gsLocal_1));
        TaskApp21 taskApp21 = new TaskApp21();
        String userinfo = taskApp21.getSeret(gsUserID, gsToken, "http://vapi.changba.com/"+destUrl);
//        MLOG("resultA1 "+destUrl);
//        MLOG("resultA2 "+userinfo);
        String url = "http://vapi.changba.com/" + destUrl+userinfo;
//        MLOG("resultA3 "+url);
        SysUtils sysUtils = new SysUtils();
        gsLocal_1 = sysUtils.getUrlString(url);
//        MLOG("resultA5 "+gsLocal_1);
        String errorcode = sysUtils.getJsonString(gsLocal_1, "errorcode");
        String result = sysUtils.getJsonString(gsLocal_1, "result");
//        MLOG(String.format("resultA6 %s(%s)", errorcode, result));
        if ("ok".equals(errorcode)) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                int length = jsonArray.length();
                BFileBase[] bFileBases = new BFileBase[length];
                for (int index = 0; index < length; index++){
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    bFileBases[index] = new BFileBase();
                    bFileBases[index].RankName = city;
                    bFileBases[index].WorksIdS = jsonobject.getString("workid");
                    String user = jsonobject.getString("user");
                    bFileBases[index].UserIdS = sysUtils.getJsonString(user, "userid");
                    bFileBases[index].UserName = sysUtils.getJsonString(user, "nickname");
                    String song = jsonobject.getString("song");
                    bFileBases[index].WorksName = sysUtils.getJsonString(song, "name");
                } ;
                MLOG(String.format("找到唱吧%s榜用户%d个", city, length));
                return bFileBases;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static synchronized BCommentInfo[] getCommentList(int counter, String userID, String worksID, String commentID){
        String destUrl = getLast(String.format("ktvbox.php?ac=getworkcomment2&num=20&start=%s&workid=%s&workowner=%s", counter, worksID, userID));

//        gsLocal_1 = "http://api.changba.com/ktvbox.php?num=20&workid=" + aux1 + "&start=" + aux2;
//        gsLocal_1 += "&workowner=49860567&smiley=1&bless=1&macaddress=" + mDeviceMac;
//        gsLocal_1 += "&ac=getworkcomment2&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + mDeviceMac + "&version=8.6.2";

        String result = writeApi(destUrl);
//        MLOG(String.format("getCommentListA A %s", destUrl));
//        MLOG(String.format("getCommentListA B %s", result));
        if (result != null) {
            try {
                SysUtils sysUtils = new SysUtils();
                String gsLocal_1 = sysUtils.getJsonString(result, "comments");
                JSONArray jsonArray = new JSONArray(gsLocal_1);
                int length = jsonArray.length();
                BCommentInfo[] bCommentInfos = new BCommentInfo[length];
                for (int index = 0; index < length; index++){
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    bCommentInfos[index] = new BCommentInfo();
                    String user = jsonobject.getString("user");
                    bCommentInfos[index].CommenterIdS = sysUtils.getJsonString(user, "userid");
//                    MLOG(String.format("getCommentListA B %s", bCommentInfos[index].CommenterIdS));
                }
//                MLOG(String.format("getCommentListA C %s", length));
//                MLOG(String.format("getCommentListA D %s", gsLocal_1));
                return bCommentInfos;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static synchronized String setComment(String userID, String worksID, String commentID, String text){
        String destUrl = getLast(String.format("ktvbox.php?ac=giveworkcomment&workowner=%s&workid=%s&content=%s", userID, worksID, URLEncoder.encode(text)));
        String result = writeApi(destUrl);
        if (result != null){
            return "ok";
        }
        MLOG(String.format("setComment A %s(%s)%s", result, text, destUrl));
        return getApiError();
    }
    public static synchronized String addCareUser(String userID){
        String destUrl = getLast(String.format("ktvbox.php?ac=followuser&follow=%s", userID));
        String result = writeApi(destUrl);
        if ("0".equals(result)){
            return "ok";
        }
        MLOG(String.format("addCareUser A %s(%s)", result, destUrl));
        return result;
    }

    public static synchronized String sendGifts(String worksID){             // 送出礼物
        String ssid = GetInsideSsid();
        String destUrl = getLast(String.format("ktvboxg.php?ac=givegift&ssid=%s&giftid=0&giftnum=1&workid=%s", ssid, worksID));
        TaskApp21 taskApp21 = new TaskApp21();
        String userinfo = taskApp21.getSeret(gsUserID, gsToken, "https://gapis.changba.com/"+destUrl);
//        MLOG("resultA1 "+destUrl);
//        MLOG("resultA2 "+userinfo);
        String url = "https://gapis.changba.com/" + destUrl+userinfo;
//        MLOG("resultA3 "+url);
        SysUtils sysUtils = new SysUtils();
//        MLOG(String.format("giftA 33 A %s", url));
        String gsLocal_1 = sysUtils.getHttpsString(url);
//        MLOG(String.format("giftA 33 B %s(%s)", gsLocal_1, url));
        String errorcode = sysUtils.getJsonString(gsLocal_1, "errorcode");
        if ("ok".equals(errorcode)) {
            String result = sysUtils.getJsonString(gsLocal_1, "result");
//            MLOG(String.format("giftA 33 V %s(%s)", errorcode, result));
            if (result != null) {
                return sysUtils.getJsonString(result, "flowerremainnum");
            }
            return "error";
        }
        return errorcode;
    }

    public static synchronized String addLikeWorks(String worksID){
        String destUrl = getLast(String.format("ktvbox.php?ac=work.worklike.likeWork&clksrc=gethottestwork&workid=%s", worksID));
        String result = writeApi(destUrl);
//        MLOG(String.format("addLikeWorksA %s(%s)", result, destUrl));
        if (result != null){
            return result;
        }
        return gsApiError;
    }
    public static synchronized String deleteWorks(String userID, String worksID){
        String destUrl = getLast(String.format("ktvbox.php?ac=deleteuserwork&workid=%s", worksID));
        String result = writeApi(destUrl);
        if ("".equals(result)){
            return "ok";
        }
        return getApiError();
    }
    public static synchronized String deletePhotoAlbum(String photoID){
        String destUrl = getLast(String.format("ktvbox.php?ac=deleteuserphoto&photoid=%s", photoID));
        String result = writeApi(destUrl);
        if ("0".equals(result)){
            return "ok";
        }
        return getApiError();
    }
    public static synchronized String setHeadPhoto(String photoID){
        String destUrl = getLast(String.format("ktvbox.php?ac=setuserheadphoto&photoid=%s", photoID));
        String result = writeApi(destUrl);
        if ("".equals(result)){
            return "ok";
        }
        SysUtils sysUtils = new SysUtils();
        String text = sysUtils.getJsonString(result, "headphoto");
        if (text.indexOf(photoID) > 0){
            return "ok";
        }
        return getApiError();
    }

    public static synchronized BAppWorks getPhotoAlbum(String userID){
        BAppWorks bPhotoWorks = new BAppWorks();
        String destUrl = getLast(String.format("ktvbox.php?ac=getuserphotolistwithlike&userid=%s", userID));
        String result = writeApi(destUrl);
//        MLOG(String.format("getPhotoAlbum A %s(%s)", destUrl, result));
        if (result != null) {
            SysUtils sysUtils = new SysUtils();
            try {
                JSONArray jsonArray = new JSONArray(result);
                int length = jsonArray.length();
                bPhotoWorks.Photos = new APhotoInfo[length];
                for (int index = 0; index < length; index++) {
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    if (jsonobject != null) {
                        bPhotoWorks.Photos[index] = new APhotoInfo();
                        bPhotoWorks.Photos[index].PhotoID = sysUtils.getJsonString(jsonobject.toString(), "photoid");
                        bPhotoWorks.Photos[index].FileUrl = sysUtils.getJsonString(jsonobject.toString(), "path");
                        bPhotoWorks.Photos[index].Intro = sysUtils.getJsonString(jsonobject.toString(), "name");
//                        lists.add(texts);
//                        MLOG(String.format("getPhotoAlbum B %s(%s)", index, text));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bPhotoWorks;
    }
    public static synchronized BAppWorks[] getPhotoWorks(String userIdS, boolean getAll){
        String lastId = "";
        List<BAppWorks> lists = new ArrayList<>();
        while (true) {
            String destUrl = getLast(String.format("ktvbox.php?ac=moment.moment.getuserpostedmoments&userid=%s&lastId=%s", userIdS, lastId));
//            MLOG("getPhotoListA getPhotoWorks A "+destUrl);
            String result = writeApi(destUrl);
            SysUtils sysUtils = new SysUtils();
            BAppWorks[] bAppWorks = getPhotoList(sysUtils.getJsonString(result, "list"));
            if (!getAll){
                return bAppWorks;
            }
            if (bAppWorks != null){
                for (int counter = 0; counter < bAppWorks.length; counter++) {
                    lists.add(bAppWorks[counter]);
                }
            }
//            MLOG(String.format("getPhotoListA getPhotoWorks B %s ", bAppWorks.length));
            if (bAppWorks.length > 0 && bAppWorks.length == 20){
                lastId = bAppWorks[bAppWorks.length - 1].WorksIdS;
//                MLOG(String.format("getPhotoListA getPhotoWorks C %s ", lastId));
                continue;
            }
            return MAPI.LISTS_ARRAYS(lists, new BAppWorks[lists.size()]);
        }
    }
    public static synchronized BAppWorks[] getHotMoment(){
        String destUrl = getLast(String.format("ktvbox.php?ac=moment.moment.gethotmomentlist&calledby=dragflush&num=20"));
        String result = writeApi(destUrl);
        return getPhotoList(result);
    }
    public static synchronized String[] getOnlinePhotos(){        // 获取当前在线的用户列表
        String destUrl = getLast(String.format("ktvbox.php?ac=online.online.getpagelist&start=0&pagesize=2"));
        String result = writeApi(destUrl);
        SysUtils sysUtils = new SysUtils();
        int onlineusernum = sysUtils.getJsonInt(result, "onlineusernum");
        String text = sysUtils.getJsonString(result, "onlineusers");
        return null;//getPhotoList(text);
    }
    public static synchronized BAppWorks[] getFollowUser(){          // 关注的
        String destUrl = getLast(String.format("ktvbox.php?ac=moment.moment.getfollowusermomentlist&calledby=dragflush&start=0&lasttag="));
        String result = writeApi(destUrl);
        return getPhotoList(result);
    }

    private static synchronized BAppWorks[] getPhotoList(String result){
//        MLOG("getPhotoListA A "+result);
        if (result != null) {
            try {
                JSONArray jsonArray = new JSONArray(result);
                int length = jsonArray.length();
                BAppWorks[] works = new BAppWorks[length];
                SysUtils sysUtils = new SysUtils();
                for (int index = 0; index < length; index++) {
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    if (jsonobject != null) {
                        String jsonText = jsonobject.toString();
                        works[index] = new BAppWorks();
                        works[index].WorksType = 49;
                        works[index].WorksIdS = sysUtils.getJsonString(jsonText, "feedid");
                        String content = sysUtils.getJsonString(jsonText, "content");
                        String moment = sysUtils.getJsonString(content, "moment");
                        works[index].Intro = sysUtils.getJsonString(moment, "content");
                        String user = sysUtils.getJsonString(moment, "user");
                        works[index].UserIdS = sysUtils.getJsonString(user, "userid");
//MLOG("getPhotoListA WorksIdS B "+works[index].WorksIdS);
                        works[index].CreateTime = MUTIL.CHANG_DATE_FORMAT(sysUtils.getJsonString(moment, "addTime"));
                        works[index].Latitude = sysUtils.getJsonString(moment, "latitude");
                        works[index].Longitude = sysUtils.getJsonString(moment, "longitude");
                        works[index].LikeQty = sysUtils.getJsonInt(moment, "likeNum");
                        works[index].CommentQty = sysUtils.getJsonInt(moment, "commentNum");
                        works[index].ListenQty = sysUtils.getJsonInt(moment, "viewNum");
                        works[index].IsOnline = sysUtils.getJsonBoolean(moment, "isOnline");
                        works[index].IsFollow = sysUtils.getJsonBoolean(moment, "isFollow");

                        String photos = sysUtils.getJsonString(moment, "photos");
                        works[index].Photos = getAPhotoInfo(photos, sysUtils);
                        works[index].Trends = getTrendsName(sysUtils.getJsonString(moment, "trends"), sysUtils);
                    }
                }
                return works;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    private static synchronized String[] getTrendsName(String photos, SysUtils sysUtils){
        try {
            JSONArray jsonArray = new JSONArray(photos);
            int length = jsonArray.length();
            if (length > 0) {
                String[] strings = new String[length];
                for (int index = 0; index < length; index++) {
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    if (jsonobject != null) {
                        String jsonText = jsonobject.toString();
                        strings[index] = sysUtils.getJsonString(jsonText, "name");
                    }
                }
                return strings;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private static synchronized APhotoInfo[] getAPhotoInfo(String photos, SysUtils sysUtils){
        try {
            JSONArray jsonArray = new JSONArray(photos);
            int length = jsonArray.length();
            if (length > 0) {
                APhotoInfo[] infos = new APhotoInfo[length];
//            MLOG("startA3 jsonArray "+jsonArray);
                for (int index = 0; index < length; index++) {
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    if (jsonobject != null) {
                        String jsonText = jsonobject.toString();
                        infos[index] = new APhotoInfo();
                        infos[index].PhotoID = sysUtils.getJsonString(jsonText, "photoid");
                        infos[index].FileUrl = sysUtils.getJsonString(jsonText, "url");          // 不知原因，这里超过60后会导致getWorks49List的 MAPI.READ_OBJECT_FILE出错
                        infos[index].FileName = String.format("%sP21_%s.jpg", MRAM.gsCachePath, infos[index].PhotoID);
                        infos[index].Width = sysUtils.getJsonInt(jsonText, "width");
                        infos[index].Height = sysUtils.getJsonInt(jsonText, "height");
                    }
                }
                return infos;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static synchronized String addLikeWorksA(String userID){
//        String a = "ktvbox.php\n" +
//                "?ac=work.worklike.likeWork&clksrc=gethottestwork&workid=1262362427&curuserid=302\n" +
//                "613029&imei=862258039403663&token=T8022aaf09f34d7e&macaddress=38%3AA4%3AED%3ABB%\n" +
//                "3A0E%3AC4&version=10.4.6&org_install_channel=market_%E5%B0%8F%E7%B1%B3&ismember=\n" +
//                "0&channelsrc=market_%E5%B0%8F%E7%B1%B3&smdeviceid=20201128102133859d823dff4a5db4\n" +
//                "9d1aa35d3e592a4201a85cec12c56ddf&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bless=1&oa\n" +
//                "id=&seret=zNNYn6-HBPh-NS6pfOai_huOfl-noADfe_zGfoczpeA&_userinfo=8712";

//        String b = "ktvbox.php\n" +
//                "?ac=getuserphotolistwithlike&userid=302613029&curuserid=302613029&imei=862258039\n" +
//                "403663&token=T8022aaf09f34d7e&macaddress=38%3AA4%3AED%3ABB%3A0E%3AC4&version=10.\n" +
//                "4.6&org_install_channel=market_%E5%B0%8F%E7%B1%B3&ismember=0&channelsrc=market_%\n" +
//                "E5%B0%8F%E7%B1%B3&smdeviceid=20201128102133859d823dff4a5db49d1aa35d3e592a4201a85\n" +
//                "cec12c56ddf&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bless=1&oaid=&seret=IyVqhhPFHpf\n" +
//                "ibAVaRh5Zw79vVwnKKJubkxCfIbzEtsw&_userinfo=6671";
        String c = "ktvbox.php\n" +
                "?ac=setuserheadphoto&photoid=940814913&curuserid=302613029&imei=862258039403663&\n" +
                "token=T8022aaf09f34d7e&macaddress=38%3AA4%3AED%3ABB%3A0E%3AC4&version=10.4.6&org\n" +
                "_install_channel=market_%E5%B0%8F%E7%B1%B3&ismember=0&channelsrc=market_%E5%B0%8\n" +
                "F%E7%B1%B3&smdeviceid=20201128102133859d823dff4a5db49d1aa35d3e592a4201a85cec12c5\n" +
                "6ddf&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bless=1&oaid=&seret=2PdcmRXonvlW1FLwFU\n" +
                "T7ORUGyTuupwLc35Nfuy2s05E&_userinfo=1059\"";
//        String d = "ktvbox.php\n" +
//                "?ac=deleteuserphoto&photoid=940814799&curuserid=302613029&imei=862258039403663&t\n" +
//                "oken=T8022aaf09f34d7e&macaddress=38%3AA4%3AED%3ABB%3A0E%3AC4&version=10.4.6&org_\n" +
//                "install_channel=market_%E5%B0%8F%E7%B1%B3&ismember=0&channelsrc=market_%E5%B0%8F\n" +
//                "%E7%B1%B3&smdeviceid=20201128102133859d823dff4a5db49d1aa35d3e592a4201a85cec12c56\n" +
//                "ddf&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bless=1&oaid=&seret=Sqk3uJIEMPSP8sOKb-7\n" +
//                "1Epcl5Pz7TN1X8A3JAYqM6cE&_userinfo=3960\"";
        String e = "\n" +
                "(agent) [0904947861134] Arguments com.changba.utils.NetworkEncrypt.a(\"ktvbox.php\n" +
                "?ac=likeworkcomment&isshortvideo=0&workid=1262368720&commentid=21984751188&curus\n" +
                "erid=302613029&imei=862258039403663&token=T8022aaf09f34d7e&macaddress=38%3AA4%3A\n" +
                "ED%3ABB%3A0E%3AC4&version=10.4.6&org_install_channel=market_%E5%B0%8F%E7%B1%B3&i\n" +
                "smember=0&channelsrc=market_%E5%B0%8F%E7%B1%B3&smdeviceid=20201128102133859d823d\n" +
                "ff4a5db49d1aa35d3e592a4201a85cec12c56ddf&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bl\n" +
                "ess=1&oaid=&seret=ggiHZQ1H9VTuy36bh0dOhLsOBseUcHubqQgngjViGbk&_userinfo=9774";
        String f = "ktvbox.php\n" +
                "?ac=likeworkcomment&isshortvideo=0&workid=1262368720&commentid=21984750836&curus\n" +
                "erid=302613029&imei=862258039403663&token=T8022aaf09f34d7e&macaddress=38%3AA4%3A\n" +
                "ED%3ABB%3A0E%3AC4&version=10.4.6&org_install_channel=market_%E5%B0%8F%E7%B1%B3&i\n" +
                "smember=0&channelsrc=market_%E5%B0%8F%E7%B1%B3&smdeviceid=20201128102133859d823d\n" +
                "ff4a5db49d1aa35d3e592a4201a85cec12c56ddf&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bl\n" +
                "ess=1&oaid=&seret=VNj3MmGe44WKihaGdEX3bAodYfs9uNqSWTnmhL-i_ms&_userinfo=1803";


        f = "ktvbox.php\n" +
                "?ac=changecoverphoto&type=work&coverid=886a59c8-ad4f-4bd5-ab41-26637576610e&work\n" +
                "id=1262372690&curuserid=302613029&imei=862258039403663&token=T8022aaf09f34d7e&ma\n" +
                "caddress=38%3AA4%3AED%3ABB%3A0E%3AC4&version=10.4.6&org_install_channel=market_%\n" +
                "E5%B0%8F%E7%B1%B3&ismember=0&channelsrc=market_%E5%B0%8F%E7%B1%B3&smdeviceid=202\n" +
                "01128102133859d823dff4a5db49d1aa35d3e592a4201a85cec12c56ddf&deviceid=38%3AA4%3AE\n" +
                "D%3ABB%3A0E%3AC4&bless=1&oaid=&seret=M0aGJsYOAW86Z5oE_iyswoRN3eSI7CFC_GRbgZuQt2E\n" +
                "&_userinfo=1504";
        String d="ktvbox.php\n" +
        "?ac=deleteuserwork&workid=1262372595&curuserid=302613029&imei=862258039403663&to\n" +
        "ken=T8022aaf09f34d7e&macaddress=38%3AA4%3AED%3ABB%3A0E%3AC4&version=10.4.6&org_i\n" +
        "nstall_channel=market_%E5%B0%8F%E7%B1%B3&ismember=0&channelsrc=market_%E5%B0%8F%\n" +
        "E7%B1%B3&smdeviceid=20201128102133859d823dff4a5db49d1aa35d3e592a4201a85cec12c56d\n" +
        "df&deviceid=38%3AA4%3AED%3ABB%3A0E%3AC4&bless=1&oaid=&seret=stLE0OlZORCmTjAb33vx\n" +
        "ddXkPZ5aktdRPMMvdhSB9n8&_userinfo=2894";

        return null;
    }


    public static synchronized String modifyUseInfo(int retry, BAppUser bAppUser) {
        // String Gender, String UserName, String Intro, String Province, String City, String Birthday

        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        ResultNet resultNet = null;
        try {
            for (int counter = 0; counter < retry; counter++){
                gsLocal_1 = "";
                if (counter == 0) {
                    gsLocal_1 = "&gender=" + bAppUser.Gender;
                }
                gsLocal_1 += "&birthday=" + bAppUser.Birthday;
                gsLocal_1 += "&location=" + URLEncoder.encode(bAppUser.Province + " " + bAppUser.City);
                gsLocal_2 = bAppUser.UserName;
                if (counter > 0) {
                    if (resultNet.message.indexOf("艺名已经被占用") >= 0) {           // 哎呀！这个艺名已经被占用了，换一个试试吧
                        if (counter < 2) {                       // 第一次
                            gsLocal_2 = bAppUser.UserName + MUTIL.GET_RANDOM_NUMBER(3);
                        } else {
                            gsLocal_2 = MUTIL.GET_RANDOM_PASSWORD();
                        }
                    }
                }
                gsLocal_1 += "&nickname=" + URLEncoder.encode(gsLocal_2);
                gsLocal_3 = bAppUser.Intro;
                if (counter > 0) {
                    if (resultNet.message.indexOf("签名中") >= 0) {                 // 你的签名中包含敏感词，请重新修改
                        if (counter == 1) {                       // 第一次
                            gsLocal_3 = bAppUser.Intro.substring(0, bAppUser.Intro.length() / 2) + MUTIL.GET_RANDOM_NUMBER(5);
                        } else if (counter == 2) {                       // 第二次
                            gsLocal_3 = bAppUser.Intro.substring(bAppUser.Intro.length() / 2, bAppUser.Intro.length()) + MUTIL.GET_RANDOM_NUMBER(5);
                        } else if (counter == 3) {
                            gsLocal_3 = bAppUser.UserName;
                        } else {
                            gsLocal_3 = MUTIL.GET_RANDOM_PASSWORD();
                        }
                    }
                }
                gsLocal_1 += "&signature=" + URLEncoder.encode(gsLocal_3);
                String destUrl = getLast(String.format("ktvbox.php?ac=setuserinfo&userid=%s", gsLocal_1));
                String result = writeApi(destUrl);

                if (result != null) {
                    return "ok";
                } else {
                    MLOG(String.format("%d修改自己出错 %s %s %s", counter, gsLocal_2, gsLocal_3, resultNet.message));
                }
                if (resultNet.message.indexOf("不能再变更") >= 0) {             // 性别已经修改过一次，不能再变更
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultNet.message;
    }

    public static synchronized String getAuthCode() {
        gsAuthSsid = GetOrgSsidFile(1);
        return (gsAuthSsid != null) ? gsAuthFile : null;
    }

    public static synchronized String[] searchUser(String user) {
        String destUrl = getLast(String.format("ktvbox.php?ac=searchuserbynickname&keyword=%s", URLEncoder.encode(user)));
        String result = writeApi(destUrl);
        MLOG(String.format("searchA %s(%s)", result, destUrl));
        if (result != null) {
            SysUtils sysUtils = new SysUtils();
            try {
                JSONArray jsonArray = new JSONArray(result);
                int length = jsonArray.length();
                String[] userIdS = new String[length];
                for (int index = 0; index < length; index++) {
                    JSONObject jsonobject = jsonArray.getJSONObject(index);
                    if (jsonobject != null) {
                        userIdS[index] = sysUtils.getJsonString(jsonobject.toString(), "userid");
                    }
                }
                return userIdS;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static synchronized String downloadHeadFile(BAppUser bAppUser) {
        return downloadHeadFile(AUserFileType.IMG_SMALL, bAppUser, false);
    }
    public static synchronized String downloadHeadFile(AUserFileType aUserFileType, BAppUser bAppUser, boolean ignoreDone) {        // 跳过ignoreDone检查
        bAppUser.HeadFile = String.format("%sH21_%s.jpg", MRAM.gsCachePath, bAppUser.UserIdS);
        String headUrl;
        if (aUserFileType == AUserFileType.IMG_SMALL){
            headUrl = bAppUser.HeadUrl.replace(".jpg", "_100_100.jpg");
        }else {
            headUrl = bAppUser.HeadUrl.replace(".jpg", "_640_640.jpg");
        }
        if (ignoreDone){                                        // 需要强制更新
            MAPI.DELETE_FILE(bAppUser.HeadFile);                         // 删除原来的文件
            MAPI.DEL_FILE_DONE(bAppUser.HeadFile);
        }
        MLOG(String.format("UserInfoA headUrl a %s", headUrl));
        if (!MAPI.IS_FILE_DONE(bAppUser.HeadFile)) {
            SysUtils sysUtils = new SysUtils();
            String result = sysUtils.getUrlFile(headUrl, bAppUser.HeadFile);
            int length = MAPI.STRING_DEC32(result);
            if (length > 0 && length == MAPI.GET_FILE_LENGTH(bAppUser.HeadFile)) {
                MAPI.SET_FILE_DONE(bAppUser.HeadFile);
            }else {
                return null;
            }
        }
        return bAppUser.HeadFile;
    }
    private static synchronized String writeApi(String destUrl){
        TaskApp21 taskApp21 = new TaskApp21();
        String userinfo = taskApp21.getSeret(gsUserID, gsToken, "http://api.changba.com/"+destUrl);
        String url = taskApp21.makeV2(0, destUrl+userinfo);     // V1 = "http://api.changba.com/"+destUrl+userinfo;
        SysUtils sysUtils = new SysUtils();
        String result = sysUtils.getUrlString(url);
        String gsLocal_1 = sysUtils.getJsonString(result, "errorcode");
        if ("ok".equals(gsLocal_1)) {
            return sysUtils.getJsonString(result, "result");
        }
        gsApiError = gsLocal_1;
//                  API校验失败  {"result":"","errorcode":"API\u6821\u9a8c\u5931\u8d25"}
        return null;
    }
    public static synchronized String getLast(String destUrl){
        return String.format("%s&curuserid=%s&imei=%s&token=%s&macaddress=%s%s%s", destUrl, gsUserID, gsImei, gsToken, gsMac, gsVersion, gsLast);
    }
//    public ResultNet WriteCommand(int type, String aux1, String aux2){
//        String gsLocal_1;
//        String gsLocal_2;
//        String gsLocal_3;
//        int g4Local_1;
//        int g4Local_2;
//        ResultNet resultNet = new ResultNet();
//        SysUtils sysUtils = new SysUtils();
//        switch (type){
//            case APPC_CHECK_LOGIN:
//                gsLocal_1 = "http://api.changba.com/ktvbox.php?&curuserid=" + gsUserID + "&specialurl=uni&token=" + gsToken + "&bless=1&macaddress=" + gsMac;
//                gsLocal_1 += "&ac=getwochangbastatus&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + gsVersion;
//                gsLocal_2 = WriteToSvr(gsLocal_1);                  // 联通沃
////MLOG("APPC_CHECK_LOGIN "+gsUserID + " " + gsToken+" "+gsLocal_2);
//                MakeStdReturn(gsLocal_2, resultNet);
//                break;
//            case APPC_GET_USER_INFO :
//                List<BAppUser> BAppUsers = new ArrayList<>();
//                BAppUser bAppUser = new BAppUser();
//                gsLocal_1 = "http://api.changba.com/ktvbox.php?&bless=1&macaddress=" + gsMac + "&userid=" + aux1;
//                gsLocal_1 += "&ac=getuserinfo&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + gsVersion;
//                //gsLocal_1 = WriteToSvr(CreateAcString("getuserinfo", aux1, ""));
//                gsLocal_2 = WriteToSvr(gsLocal_1);
////MLOG("GET_USER_INFO "+gsLocal_1+" " + gsLocal_2);
//
//                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
//                    bAppUser.UserIdS = aux1;
//                    bAppUser.UserName = MUTIL.GET_JSON_STRING(resultNet.nextJason, "nickname");
//                    bAppUser.ChangBaID = MUTIL.GET_JSON_STRING(resultNet.nextJason, "accountid");
//                    bAppUser.Gender = sysUtils.getJsonInt(resultNet.nextJason, "gender");
//                    bAppUser.Intro = MUTIL.GET_JSON_STRING(resultNet.nextJason, "title");
//                    if ("".equals(bAppUser.Intro)) {
//                        bAppUser.Intro = MUTIL.GET_JSON_STRING(resultNet.nextJason, "signature");
//                    }
//                    bAppUser.HeadUrl = MUTIL.GET_JSON_STRING(resultNet.nextJason, "headphoto");
//                    bAppUser.Birthday = MUTIL.GET_JSON_STRING(resultNet.nextJason, "birthday");
//                    String location = MUTIL.GET_JSON_STRING(resultNet.nextJason, "location");
//                    if (!"".equals(location)) {
//                        location = location.replace("+", " ");
//                        String[] split = location.split(" ");
//                        if (split.length > 0) {
//                            bAppUser.Province = split[0];
//                            if (split.length > 1) {
//                                bAppUser.City = split[1];
//                            }
//                        }else {
//                            MLOGE(String.format("App33 location:%s", location));
//                        }
//                    }else {
//                        bAppUser.Province = MUTIL.GET_JSON_STRING(resultNet.nextJason, "province");
//                        bAppUser.City = MUTIL.GET_JSON_STRING(resultNet.nextJason, "city");
//
//                    }
//                    bAppUser.longitude = MUTIL.GET_JSON_STRING(resultNet.nextJason, "longitude");
//                    bAppUser.latitude = MUTIL.GET_JSON_STRING(resultNet.nextJason, "latitude");
//                }
////                gsLocal_1 = "http://api.changba.com/ktvbox.php?curuserid=" + gsUserID + "&token=Taf2e516861ecfe4&bless=1&macaddress=";
////                gsLocal_1 += gsMac + "&userid=" + aux1 + "&&ac=getuserrelationnum&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + gsVersion;
////                gsLocal_2 = WriteToSvr(gsLocal_1);
//                gsLocal_2 = WriteToSvr(CreateAcString("getuserrelationnum", aux1, ""));
////MLOG("getuserrelationnum "+gsLocal_2);
//                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
//
//                    bAppUser.FansQty = sysUtils.getJsonInt(resultNet.nextJason, "fansnum");
//                    bAppUser.CareQty = sysUtils.getJsonInt(resultNet.nextJason, "friendsnum");
////MLOG("CareQty "+BAppUser.FansQty+" "+BAppUser.CareQty);
////
////                    gsLocal_2 = MUTIL.GET_JSON_STRING(resultNet.nextJason, "user_events");
//////MDWORD(0x9a);MLOG(gsLocal_1);MLOG(gsLocal_2);
////                    BAppUser.NewNoticeQty = MUTIL.GET_JSON_STRING(gsLocal_2, "newnotice_num");
//
////MLOG(BAppUser.NewNoticeQty);
//                }
//                gsLocal_2 = WriteToSvr(CreateAcString("getuserstatistics", aux1, ""));
////MDWORD(0xaa);MLOG(gsLocal_1);
//                if (MakeStdReturn(gsLocal_2, resultNet) == true) {
//                    bAppUser.WorksQty = MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(resultNet.nextJason, "worknum"));
//                    bAppUser.ListenQty = MAPI.STRING_DEC32(MUTIL.GET_JSON_STRING(resultNet.nextJason, "listennum"));
//                }
////MLOG("唱吧用户：" + BAppUser.UserName +" "+ BAppUser.WorksQty +" "+ BAppUser.Intro +" "+ BAppUser.Province +" "+ BAppUser.City +" "+ BAppUser.HeadUrl);
//                BAppUsers.add(bAppUser);
//                resultNet.result = BAppUsers;
//                break;
//            case APPC_GET_SONG_LIST:
//
//                break;
//            case APPC_GET_COMMENT_LIST :
//            case APPC_GET_COMMENT_USERID:
//
//                break;
//            case APPC_MODIFY_ME:
//                gsLocal_1 = WriteToSvr(CreateAcString("setuserinfo", aux1, ""));
//                MakeStdReturn(gsLocal_1, resultNet);
////MLOG("ME "+aux1);
////MLOG("APPC_MODIFY_ME "+gsLocal_1);
//                break;
//            case APPC_GET_AUTH_CODE:
//                gsAuthSsid = GetOrgSsidFile(1);
//                break;
//        }
//        return resultNet;
//    }
//    public BAppComment MakeACommInfo(JSONArray jsonArray, int counter){
//        BAppComment bCommInfo = new BAppComment();
//        SysUtils sysUtils = new SysUtils();
//        try {
//            JSONObject jsonobject = jsonArray.getJSONObject(counter);
//            bCommInfo.aUserInfo = new BAppUser();
//            String gsLocal_2 = jsonobject.getString("user");
//            bCommInfo.aUserInfo.UserIdS = MUTIL.GET_JSON_STRING(gsLocal_2, "userid");
//            bCommInfo.aUserInfo.UserName = MUTIL.GET_JSON_STRING(gsLocal_2, "nickname");
//            bCommInfo.aUserInfo.HeadUrl = MUTIL.GET_JSON_STRING(gsLocal_2, "headphoto");
//            bCommInfo.aUserInfo.Gender = sysUtils.getJsonInt(gsLocal_2, "gender");
////MLOG("content1 " + bCommInfo.BAppUser.UserName);
////MLOG("content2 " + bCommInfo.BAppUser.HeadUrl);
//            bCommInfo.commentID = jsonobject.getString("commentid");
//            bCommInfo.content = jsonobject.getString("content");
//            bCommInfo.createTime = MUTIL.CHANG_DATE_FORMAT(jsonobject.getString("time"));
//            bCommInfo.totalReply = jsonobject.getString("replynum");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return bCommInfo;
//    }
    public static synchronized ResultNet WriteCommand(int type, String aux1, String aux2, String aux3){
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        ResultNet resultNet = new ResultNet();
        switch (type) {
            case APPC_USER_LOGIN:
                gsLocal_1 = MUTIL.GET_MD5_STRING(gsAuthSsid + "ba!se");
                gsLocal_2 = gsLocal_1.substring(0, 10);
                gsLocal_1 = MUTIL.GET_MD5_STRING(aux2);
                if (aux3.startsWith("c2")){
                    gsLocal_3 = "";
                }
                else {
                    gsLocal_3 = URLEncoder.encode(aux3);
                }
                gsLocal_1 = "https://secure.changba.com/ktvboxs.php?ac=llogin&md5pwd=" + gsLocal_1 + "&email="+aux1+"&ssid="+gsLocal_2+"&captcha=" + gsLocal_3;
                gsLocal_1 += "&channelsrc=changba&deviceid="+ gsMac +"&bless=1&macaddress="+ gsMac +gsVersion;
                gsLocal_3 = httpsConnectionGet(gsLocal_1);
                if (MakeStdReturn(gsLocal_3, resultNet)){
                    MLOG("KgChangBa APPC_USER_LOGIN "+resultNet.message+"_ "+gsLocal_3);
                    gsUserID = MUTIL.GET_JSON_STRING(resultNet.nextJason, "userid");
                    gsToken = MUTIL.GET_JSON_STRING(resultNet.nextJason, "token");
                    if (!"".equals(gsUserID) && !"".equals(gsToken)){
                        LoginFlag = gsUserID + ":" + gsToken.substring(1, gsToken.length());
                        MLOG("KgChangBa LoginFlag "+ LoginFlag +" "+gsToken);
                    }
                }
                break;
            case APPC_WEIBO_AUTH:
                if ("".equals(aux2)) {
                    aux2 = GetInsideSsid();
                    aux3 = "";
                }
                gsLocal_2 = "https://secure.changba.com/ktvboxs.php?ac=ssoentry&sso_code="+aux1+"&sso_type=sina&ssid="+aux2+"&captcha=" + URLEncoder.encode(aux3);
                gsLocal_2 += "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid="+ gsMac +"&bless=1&macaddress="+ gsMac +gsVersion;
                gsLocal_3 = httpsConnectionGet(gsLocal_2);
                MakeStdReturn(gsLocal_3, resultNet);
                MLOG("APPC_WEIBO_AUTH "+aux2+"_"+aux3+"_"+resultNet.message+"_ "+gsLocal_3);
                break;
            case APPC_WEIBO_REGISTER:
                gsLocal_1 = "https://secure.changba.com/ktvboxs.php?ac=changbaregister&sso_code="+aux1+"&Gender="+aux3+"&sso_openid="+aux2+"&sso_type=sina&nickname=";
                gsLocal_1 += MUTIL.GET_RANDOM_PASSWORD() + "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid="+ gsMac +"&bless=1&macaddress="+ gsMac +gsVersion;
                gsLocal_3 = httpsConnectionGet(gsLocal_1);
                MakeStdReturn(gsLocal_3, resultNet);
                MLOG("APPC_WEIBO_REGISTER "+gsLocal_3+" "+resultNet.message);
                break;
            case APPC_MODIFY_ACCOUNTID:
                gsLocal_2 = "https://secure.changba.com/ktvboxs.php?ac=iinituseraccountid&token="+gsToken+"&curuserid="+gsUserID+"&password=" + MUTIL.GET_MD5_STRING(aux2) + "&accountid=";
                gsLocal_2 += aux1 + "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid="+ gsMac +"&bless=1&macaddress="+ gsMac +gsVersion;
                gsLocal_3 = httpsConnectionGet(gsLocal_2);
                MakeStdReturn(gsLocal_3, resultNet);
                MLOG("APPC_MODIFY_ACCOUNTID "+gsLocal_3+" "+resultNet.message);
                break;
            case APPC_PUT_FLOWER:
                if ("".equals(aux2)) {
                    aux2 = GetInsideSsid();
                    aux3 = "";
                }
                gsLocal_1 = "https://gapis.changba.com/ktvboxg.php?ac=givegift&curuserid=" + gsUserID + "&ssid=" + aux2 + "&giftid=0&workid=" + aux1 + "&giftnum=1&token=";
                gsLocal_1 += gsToken + "&captcha=" + URLEncoder.encode(aux3) + "&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid=" + gsMac + "&bless=1&macaddress=" + gsMac + gsVersion;
                gsLocal_2 = httpsConnectionGet(gsLocal_1);
                if (MakeStdReturn(gsLocal_2, resultNet)) {
                    resultNet.message = MUTIL.GET_JSON_STRING(resultNet.nextJason, "flowerremainnum");
                }
                MLOG("APPC_PUT_FLOWER "+gsLocal_2 +" "+resultNet.message);
                break;
            case APPC_PUT_COMMENT:
                gsLocal_1 = "http://api.changba.com/ktvbox.php?content=" + URLEncoder.encode(aux3) + "&curuserid=" + gsUserID + "&workid=" + aux2;
                gsLocal_1 += "&token=" + gsToken + "&bless=1&macaddress=" + gsMac + "&ac=giveworkcomment&workowner=" + aux1;
                gsLocal_1 += "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + gsVersion;

                gsLocal_3 = WriteToSvr(gsLocal_1);
                MakeStdReturn(gsLocal_3, resultNet);
//MLOG("APPC_PUT_COMMENT " +gsUserID+" "+ gsLocal_1+" "+ gsLocal_3 +" "+resultNet.message);

//                gsLocal_1 = "http://api.changba.com/ktvbox.php?ac=getsong2&songid=454&bless=1&macaddress=" + gsMac + "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + gsVersion;
//                gsLocal_3 = WriteToSvr(gsLocal_1);
//MLOG("getsong2 "+gsLocal_3);
                break;

        }
        return resultNet;
    }
    public static synchronized String CreateAcString(String type, String userID, String start){
        String gsLocal_1 = "http://api.changba.com/ktvbox.php?";
        if (!"".equals(start)){
            gsLocal_1 += "num=20&start=" + start;
        }
        gsLocal_1 += "&curuserid=" + gsUserID + "&token=" + gsToken + "&bless=1&macaddress=" + gsMac + "&userid=" + userID;
        return gsLocal_1 + "&ac=" + type + "&channelsrc=market_%E7%99%BE%E5%BA%A6&deviceid=" + gsMac + gsVersion;
    }
    public static synchronized boolean MakeStdReturn(String gsLocal_1, ResultNet netResult) {
        String gsLocal_2 = MUTIL.GET_JSON_STRING(gsLocal_1, "errorcode");
        if ("ok".equals(gsLocal_2)) {
            netResult.nextJason = MUTIL.GET_JSON_STRING(gsLocal_1, "result");
//MDWORD(0xb1);MLOG(netResult.nextJason);
            return true;
        }
        netResult.message =  gsLocal_2 + ":" + MUTIL.GET_JSON_STRING(gsLocal_1, "error");
        netResult.sucess = false;
        return false;
    }

    public static synchronized String WriteToSvr(String destUrl) {
        String gsLocal_1 = "";
        BufferedInputStream bis = null;
        HttpURLConnection mHttpUrl=null;
        URL url = null;
        byte[] gLocal_Buffer = new byte[0x200000+1460];
        destUrl += MUTIL.GET_SERET_USER_INFO(destUrl);
//        MLOG("WriteToSvr "+destUrl);
        try {
            //          MLOG(destUrl);
//MLOG("网络3");
            url = new URL(destUrl);
            mHttpUrl = (HttpURLConnection) url.openConnection();
            mHttpUrl.setConnectTimeout(30000);
            mHttpUrl.setReadTimeout(30000);
            mHttpUrl.setRequestProperty("Cb-X-Seqid", "t=4;n=15;d=0");
            mHttpUrl.setRequestProperty("Connection", "Keep-Alive");
            mHttpUrl.setDoInput(true);
//MLOG("网络4");
            int responseCode = mHttpUrl.getResponseCode();
            //         MDWORD(0xe1);MDWORD(responseCode);
            if (responseCode >= 200 || responseCode < 300) {
                bis = new BufferedInputStream(mHttpUrl.getInputStream());
            }
            else {
                bis = new BufferedInputStream(mHttpUrl.getErrorStream());
            }
//MLOG("网络5");

            int size = 0;
            int g4Local_1 = 0;
            while ((size = bis.read(gLocal_Buffer, g4Local_1, 1460)) != -1) {
                if (size > 0){
                    g4Local_1 += size;
                    if (g4Local_1 >= 0x200000){
                        break;
                    }
                }
            }
            bis.close();
            if (g4Local_1 > 0){
                gsLocal_1 = new String(gLocal_Buffer, 0, g4Local_1, "utf-8");
            }
            mHttpUrl.disconnect();
//MLOG("网络11");
        } catch (IOException e) {
        }
//MLOG("网络12");
        return gsLocal_1;
    }
    private static synchronized String httpsConnectionGet(String urlPath){
        urlPath += MUTIL.GET_SERET_USER_INFO(urlPath);
        String re_str = "";
        try {
            URL url = new URL(urlPath);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.connect();
            StringBuilder builder = new StringBuilder();
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            while((line = reader.readLine())!=null){
                builder.append(line);
            }
            reader.close();
            connection.disconnect();
            re_str = builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re_str;
    }
    private static synchronized String GetInsideSsid(){
        String ssidInput  =  GetOrgSsidFile(0);
//System.out.println("ssid：" + ssidInput);
        return MUTIL.GET_MD5_STRING(ssidInput + "ba!se").substring(0,10);
    }



    private static synchronized String GetOrgSsidFile(int mode){
        String gsLocal_1;
        try {
            if (mode == 0) {
                gsLocal_1 = "http://api.changba.com/login/check_code.php?&action=ssoentry&method=sina&channelsrc=market_%E8%85%BE%E8%AE%AF&deviceid=64%3Acc%3A2e%3A4d%3Ad9%3A94&bless=1"+gsVersion+"&macaddress=64%3Acc%3A2e%3A4d%3Ad9%3A94";
            }
            else {
                gsLocal_1 = "http://api.changba.com/login/check_code.php?bless=1&channelsrc=changba&macaddress=" + gsMac + "&deviceid=" + gsMac + gsVersion+"&action=llogin&method=ktv";
            }
            URLConnection v0 = new URL(gsLocal_1).openConnection();;
            InputStream v3 = v0.getInputStream();
            ByteArrayOutputStream v4 = new ByteArrayOutputStream();
            byte bs [] = new byte[10];
            int size;
            while ((size = v3.read(bs))!=-1){
                v4.write(bs,0,size);
            }
            byte[] v5 = v4.toByteArray();
            //输出验证码图片  好像c22a1175开头不需要验证码
            File cpFile = new File(gsAuthFile);
            FileOutputStream out = new FileOutputStream(cpFile);
            out.write(v5);
            out.flush();
            out.close();
            //System.out.println("验证码储存位置："+cpFile.getAbsolutePath());
            String v1 = new String(v5);
            // System.out.println(v1);
            int v6 = v1.length();
            if(v6 < 26) {
                throw new Exception("获取验证码失败,请重新尝试");
            }
            String ssid = "";
            if("0123456789".equals(v1.substring(v6 - 10, v6))) {
                ssid = v1.substring(v6 - 26, v6 - 10);
                System.out.println("ssid："+ssid);
            }
            return ssid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static synchronized byte[] MixAccountToBuffer(String mixAccount, String userID) {     // "11641250,fd4474de357019af2"
        byte gpLocal_1[];
        gpLocal_1 = new byte[12];
        String[] params = mixAccount.split(",");
        if (params.length > 1){
            MAPI.DWORD_BUFF8(MAPI.STRING_DEC32(params[0]), 0, gpLocal_1);
            SubUtils sysUtils = new SubUtils();
            sysUtils.fromAsciiStringToHex(params[1] + "0", 8, 4, gpLocal_1);
//MBAPP.MLOG("MixAccountToBuffer "+ mixAccount + " "+gpLocal_1);
        }
        return gpLocal_1;
    }

    public static synchronized String Base64MixAccount(String base64) {
        if (base64 != null && !"".equals(base64)) {
            String gsLocal_1;
            byte gpLocal_1[];
            SubUtils sysUtils = new SubUtils();
            try {
                gpLocal_1 = CodeBase64.decode(base64.getBytes());
                if (gpLocal_1.length >= 12) {
                    gsLocal_1 = sysUtils.fromHexStringAscii(8, 4, gpLocal_1);
//MBAPP.MLOG("Base64MixAccount "+ gsLocal_1);
                    gsLocal_1 = gsLocal_1.substring(0, gsLocal_1.length() - 1);
                    return String.format("%d,%s", MAPI.BUFF8_DWORD(0, gpLocal_1), gsLocal_1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MLOGE("KgChangBa Base64MixAccount error "+base64);
        return "";
    }


    public static synchronized String SetLongitudeLatitude(int init){
//        int g4Local_1 = 0;
//        do {
//            String gsLocal_1 = MUTIL.GET_CITY_LOCAL(mRankCounter);
//            if (init == 0) {
//                mRankCounter += 1;
//                CFileDbs aFileDbs = new CFileDbs(gsRankDbsFile);
//                aFileDbs.mCounter = mRankCounter;
//                aFileDbs.writeCounter();
//                aFileDbs.close();
//            }
//            String[] params = gsLocal_1.split(" ");
//            if (params.length >= 4) {
//                gsLatitude = params[2];
//                gsLongitude = params[3];
//                return params[0] + " " +params[1];
//            }
//        } while (++g4Local_1 < 10);
        return "";
    }
}
